package com.umeox.watch.moto.dataservice.observer;

import android.content.ContentValues;
import android.database.ContentObserver;
import android.os.Handler;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.mqtt.base.AError;
import com.umeox.moto.mqtt.base.ARequest;
import com.umeox.moto.mqtt.base.AResponse;
import com.umeox.watch.moto.apiclient.model.GalleryDTO;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.dataservice.base.BaseApp;
import com.umeox.watch.moto.dataservice.mqtt.interfaces.IPublishListener;
import com.umeox.watch.moto.dataservice.services.ApiService;

import java.util.ArrayList;
import java.util.List;

/**
 * 监听K8C相册上传到亚马孙服务器的变化
 */

public class GalleryContentObserver extends ContentObserver {
    private static final String TAG = GalleryContentObserver.class.getSimpleName();

    private GalleryContentObserver(Handler handler) {
        super(handler);
    }

    public static GalleryContentObserver getInstance() {
        return Holder.INSTANCE;
    }

    public void registerGalleryContentObserver() {
        unregisterGalleryContentObserver();
        try {
            BaseApp.getInstance().getContentResolver().registerContentObserver(DataProvider.GalleryProvider.getUri(), false, Holder.INSTANCE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void unregisterGalleryContentObserver() {
        try {
            BaseApp.getInstance().getContentResolver().unregisterContentObserver(Holder.INSTANCE);
        } catch (Exception ignored) {
        }
    }

    /**
     * 当所监听的Uri发生改变时，就会回调此方法
     *
     * @param selfChange 此值意义不大 一般情况下该回调值false
     */
    @Override
    public void onChange(boolean selfChange) {
        List<GalleryDTO> temp = getNotUploadedPhotos();
        Logger.i(TAG + "-------------相册发送改变， " + (temp != null ? temp.size() : 0) + "张照片未上报-------------");
        if (temp != null && !temp.isEmpty()) {
            ApiService.uploadALB(temp, new IPublishListener() {
                @Override
                public void onSuccess(ARequest request, AResponse response) {
                    Logger.i("上报ALB事件成功");
                    updateContent(temp);
                }

                @Override
                public void onFailure(ARequest request, Object message, AError error) {
                    Logger.i("上报ALB事件失败，原因：" + error.getMsg());
                }
            });
        }
    }

    private List<GalleryDTO> getNotUploadedPhotos() {
        List<ContentValues> photos = DataProvider.getNotUploadedPhotos();
        if (photos != null && !photos.isEmpty()) {
            List<GalleryDTO> result = new ArrayList<>(photos.size());
            for (ContentValues photo : photos) {
                GalleryDTO dto = new GalleryDTO();
                dto.id = photo.getAsLong(DataProvider.GalleryProvider.ID);
                dto.imageName = photo.getAsString(DataProvider.GalleryProvider.IMAGE_NAME);
                dto.imagePath = photo.getAsString(DataProvider.GalleryProvider.IMAGE_PATH);
                dto.imageUrl = photo.getAsString(DataProvider.GalleryProvider.IMAGE_SERVER_PATH);
                dto.imageSize = photo.getAsLong(DataProvider.GalleryProvider.IMAGE_SIZE);
                dto.takTime = photo.getAsLong(DataProvider.GalleryProvider.TAKE_TIME);
                dto.uploadTime = photo.getAsLong(DataProvider.GalleryProvider.UPLOAD_TIME);
                result.add(dto);
            }
            return result;
        }
        return null;
    }

    private void updateContent(List<GalleryDTO> result) {
        if (result == null || result.isEmpty()) {
            return;
        }
        try {
            String[] ids = new String[result.size()];
            int index = 0;
            for (GalleryDTO dto : result) {
                ids[index] = String.valueOf(dto.id);
                index++;
            }
            Logger.w(TAG + "->更新数据库相应行数：" + DataProvider.resetAlbumUploadFlag(ids));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class Holder {
        private static final GalleryContentObserver INSTANCE = new GalleryContentObserver(new Handler());
    }
}
